package xyz.ibenben.zhongdian.system.service.sys.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.system.dao.sys.SysUserRoleDao;
import xyz.ibenben.zhongdian.system.entity.sys.SysUserRole;
import xyz.ibenben.zhongdian.system.service.sys.SysUserRoleService;

import javax.annotation.Resource;

/**
 * 系统用户角色服务实现类
 * 系统级用户所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如添加用户角色、根据用户主键删除记录等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
    @Resource
    private SysUserRoleDao sysUserRoleDao;

    /**
     * addUserRole用户角色记录
     *
     * @param userRole 实体
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @SystemServiceLog(description = "addUserRole用户角色记录")
    public void addUserRole(SysUserRole userRole) {
        //删除
        this.deleteByUserId(userRole.getUserId());
        //添加
        String[] roleIds = userRole.getRoleIds().split(Constants.COMMA);
        for (String roleId : roleIds) {
            //组装实体
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setUserId(userRole.getUserId());
            sysUserRole.setRoleId(Long.parseLong(roleId));
            //保存实体
            sysUserRoleDao.insert(sysUserRole);
        }
    }

    /**
     * deleteByUserId用户角色记录
     *
     * @param userId 用户主键
     * @return 是否删除成功
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    @SystemServiceLog(description = "deleteByUserId用户角色记录")
    public int deleteByUserId(Object userId) {
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        //根据用户主键删除记录
        return sysUserRoleDao.deleteByExample(example);
    }

}
